package com.gulimall.member.interceptor;

import com.common.constant.LoginConstant;
import com.common.to.MemberTo;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author Rookie-6688
 * @Description
 * @Create 2021-04-27 16:32
 */
public class MemberInterceptor implements HandlerInterceptor {

    public static final ThreadLocal<MemberTo> userMap = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 防止在消息队列解锁库存时发送的order远程调用没有携带用户被拦截，所以这里放行（消息队列本身就不携带用户消息的Cookie，所以这里向ware发送的feign线程请求里塞Cookie还是不行）
        String uri = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/member/**", uri);
        if(match){
            return true;
        }

        MemberTo memberTo = (MemberTo) request.getSession().getAttribute(LoginConstant.LOGIN_USERNAME);
        if(memberTo == null){
            request.getSession().setAttribute("msg","请先登陆");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }else{
            userMap.set(memberTo);
//            request.getSession().setAttribute(LoginConstant.LOGIN_USERNAME, memberTo);
            return true;
        }
    }
}
